/*
* @file_name: task_executor.h
* @date: 2021/08/30
* @author: oaho
* Copyright @ hz oaho, All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _OAHO_TASK_EXECUTOR_H
#define _OAHO_TASK_EXECUTOR_H
#include <type_traits>
#include <functional>
#include <memory>
#include <thread>
#include <atomic>
#include <chrono>
#include <mutex>
#include <list>
struct async_t {};
struct sync_t{};
using task_t = std::function<void()>;


template<typename T>
struct executaor_traits {
	using type = typename T::executor_tag;
};

/* sync executor */
class sync_executor {
public:
	using executor_tag = sync_t;
public:
	inline void start() {}
	inline void stop() {}
	template<typename Func>
	inline void put(Func&& f) { f(); }
};


/* async executor */
template<typename mutex_t, typename alloc_t = std::allocator<task_t>>
class async_executor {
public:
	using executor_tag = async_t;
	using task_t = std::function<void()>;
	using mutex_type = typename mutex_t::mutex_type;
public:
	async_executor();
	~async_executor();
	inline void start();
	inline void stop();
	template<typename Func>
	inline void put(Func&& f);
private:
	void run();
private:
	std::list<task_t, alloc_t> task_que;
	std::unique_ptr<std::thread> _th_executor;
	std::atomic<bool> quit;
	mutex_type mtx;
};


template<typename _policy_>
class task_executor {
public:
	using execute_policy = _policy_;
	using executor_tag = typename _policy_::executor_tag;
public:
	inline void start();
	inline void stop();
public:
	template<typename Func, typename...Args> void async(Func&&, Args&&...);
private:
	execute_policy _execute_;
};


#endif